/**
 * Created by lijizhuang on 16/9/19.
 */
define(['jquery', 'underscore', 'backbone', 'bootstrap', 'common', 'url', 'text!modules/roomTypesMgr/roomTypeListView.html', 'modules/roomTypesMgr/roomTypeRow',
        'modules/roomTypesMgr/modal/newRoomType'],
    function ($, _, Backbone, Bootstrap, Common, Url, RoomTypeListViewTemplate, RoomTypeRow, NewRoomTypeView) {
        var roomTypeList = Backbone.View.extend({
            tagName: 'div',
            className: 'roomTypeInfo',
            template: _.template(RoomTypeListViewTemplate),

            initialize: function () {
                this.collection.on({
                    'add': _.bind(function(model, collection, options){
                        this.render();
                    }, this),
                    'remove': _.bind(function(model, collection, options){
                        this.render();
                    }, this),
                    'change': _.bind(function (model, collection, options) {
                        this.render();
                    }, this)
                });

                _bnb = null;

                Common.sendAjaxRequest(Url.currentBnb, "", function (data) {
                    if (data && data.Content && data.Content.length > 0) {
                        _bnb = JSON.parse(data.Content);
                    }
                }, function (data) {
                }, false);

            },

            events: {
                'click #addRoomType': 'onAddRoomTypeClick'
            },

            onAddRoomTypeClick: function () {
                var newRoomTypeView = new NewRoomTypeView({collection:this.collection, bnbId:_bnb.BnbId});
                if ($('body').find('#newRoomType').length === 0) {
                    $('body').append(newRoomTypeView.render().el);
                }
                else {
                    $('#newRoomType').replaceWith(newRoomTypeView.render().el);
                }

                $("#newRoomType").modal({backdrop: 'static', keyboard: false});
            },

            changeRank: _.bind(function (model, val, options) {
                this.render();
            },this),

            render: function () {
                this.$el.html(this.template);

                //对房型集合按照房型排名进行排序
                this.collection.comparator = function(model) {
                    return model.get('sort');
                };

                this.collection.sort();

                this.collection.each(_.bind(function (roomType) {
                    var roomTypeRow = new RoomTypeRow({model: roomType, collection: this.collection});
                    this.$el.find('.roomTypeTable').find('tbody').append(roomTypeRow.render().el);
                }, this));

                return this;
            }
        });

        return roomTypeList;
    });